using System.Diagnostics;

namespace DmServer.Handlers.Handlers;

public class GetScreenDataBmp : IMessageHandler
{
    public void HandleMessage(StringRequestInfo? request, TcpSessionClient client, DmSoft dm)
    {
        if (request?.Parameters == null || request?.Parameters.Length != 4)
            client.SendAsync(CryptoHelper.EncryptDES("协议命令错误！"));

        int.TryParse(request?.Parameters?[0], out int x1);
        int.TryParse(request?.Parameters?[1], out int y1);
        int.TryParse(request?.Parameters?[2], out int w);
        int.TryParse(request?.Parameters?[3], out int h);
        Stopwatch stopwatch = new Stopwatch();
        // 启动计时
        stopwatch.Start();
        var result = dm.GetScreenDataBmp(0, 0, w, h, out int data, out int size);
        // 停止计时
        stopwatch.Stop();
        client.Logger.Info($"代码段耗时: {stopwatch.ElapsedMilliseconds} 毫秒");
        byte[] picData = new byte[size];
        nint ptr = new nint(data);
        Marshal.Copy(ptr, picData, 0, size);
        //将 byte 数组转换为 Image 对象
        using MemoryStream ms = new MemoryStream(picData);
        var bytes = ms.ToArray();

        client.Logger.Info("GetScreenDataBmp：" + result.ToString());
        // 回复客户端消息
        client.SendAsync(CryptoHelper.EncryptDES(bytes));
    }
}
